﻿using Groove.Core.Infrastructure;
using Meting4Net.Core;
using Newtonsoft.Json;
using SchwabenCode.QuickIO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace Groove.Core.WebSongFinder
{
    public class WebSongFinder
    {
        private static ServerProvider ServerProvider => ServerProvider.Kugou;
        public static List<WebSong> Search(string name)
        {
            try
            {
                if (string.IsNullOrEmpty(name)) return null;
                var meting = new Meting(ServerProvider);
                var json = meting.FormatMethod().Search(name, new Meting4Net.Core.Models.Standard.Options()
                {
                    page = 1,
                    limit = 20
                });
                return JsonConvert.DeserializeObject<List<WebSong>>(json);
            }
            catch (Exception ex)
            {
                LogWriter.Error($"Search Song Error,Source:{ServerProvider}", ex);
                return null;
            }
        }

        private static string GetUrl(string urlId)
        {
            try
            {
                var meting = new Meting(ServerProvider);
                var json = meting.FormatMethod().Url(urlId, 128);
                return JsonConvert.DeserializeObject<SongUrl>(json)?.Url;
            }
            catch (Exception ex)
            {
                LogWriter.Error($"Get song url error,Source:{ServerProvider}", ex);
                return null;
            }
        }

        public static async Task<bool> DownLoadAsync(string urlId, string fileName)
        {
            try
            {
                if (await QuickIOFile.ExistsAsync(fileName)) return false;
                var url = GetUrl(urlId);
                if (string.IsNullOrEmpty(url)) return false;
                var http = new HttpClient();
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                var response = await http.SendAsync(request);
                response.EnsureSuccessStatusCode();
                using (var fs = File.Open(fileName, FileMode.Create))
                {
                    using (var ms = await response.Content.ReadAsStreamAsync())
                    {
                        await ms.CopyToAsync(fs);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                LogWriter.Error("Download song Error", ex);
                return false;
            }
        }
    }
}
